package org.lojzes.minstruts.servlet;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lojzes.minstruts.mappings.Mapping;
import org.lojzes.minstruts.reflect.ClassFull;

public class ActionServlet extends HttpServlet{
    private static Log log = LogFactory.getLog(ActionServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Map<String,Mapping> actionMap = (Map<String,Mapping>)req.getServletContext().getAttribute("actionMap");
		String servletPath =req.getServletPath().substring(0,req.getServletPath().length()-3);
		log.info("servletPath====>>"+servletPath);
		Mapping mapping = actionMap.get(servletPath);
		if(null == mapping){
			resp.sendError(404,"未找到所指定的资源！");
			return;
		}
		String actionClass = mapping.getActionClass();
		String actionName = mapping.getActionName();
		String method = getMethod(servletPath, actionName, mapping);
 		String forward = ClassFull.getInstance().fullAction(actionClass,method,req,resp);
 		req.getRequestDispatcher(forward).forward(req, resp);
	}

	/**
	 * 得到方法名称
	 * @param servletPath
	 * @param actionName
	 * @param mapping
	 * @return
	 */
	private static String getMethod(String servletPath,String actionName,Mapping mapping) {
        String parameter= servletPath.substring(actionName.length(),servletPath.length());
        String method = mapping.getMappedMethod().get(parameter);
        return method;
	}
}
